import accuracy_function from '../accuracy_function.js';

export default {

	/**
	 * 获取当前页面栈
	 */
	prePage() {
		let pages = getCurrentPages();
		let prePage = pages[pages.length - 2];
		// #ifdef H5
		return prePage;
		// #endif
		return prePage.$vm;
	},

	/**
	 * 加法精度计算
	 * @param {Object} number 数字
	 */
	add(a, b) {
		return accuracy_function.bcadd(a, b);
	},

	/**
	 * 减法精度计算
	 * @param {Object} number 数字
	 */
	sub(a, b) {
		return accuracy_function.bcsub(a, b);
	},

	/**
	 * 乘法精度计算
	 * @param {Object} number 数字
	 */
	mul(a, b) {
		return accuracy_function.bcmul(a, b);
	},

	/**
	 * 除法精度计算
	 * @param {Object} number 数字
	 */
	div(a, b) {
		return accuracy_function.bcdiv(a, b);
	},
	/**
	 * 获取系统信息
	 */
	sys() {
		let sys = uni.getSystemInfoSync();

		let data = {

			top: sys.statusBarHeight,
			height: sys.statusBarHeight + uni.upx2px(90),
			screenHeight: sys.screenHeight,
			platform: sys.platform,
			model: sys.model,
			windowHeight: sys.windowHeight,
			windowBottom: sys.windowBottom
		};


		return data;
	},

	/**
	 * 修改标题栏
	 * @param {Object} text 新标题
	 * @param {Object} barColor 导航栏颜色
	 */
	title(text = '', frontColor = '', backgroundColor = '') {
		if (text) {
			uni.setNavigationBarTitle({
				title: text
			});
		}
		var setbar = {
			frontColor,
			backgroundColor
		}
		if (setbar != "{}") {
			uni.setNavigationBarColor(setbar);
		}
	},
	/**
	 * 数字格式化
	 * @param {Object} number 数字
	 * @param {Object} type 类型 thousand:万,hundred:百
	 */
	numFormat(number, type) {
		//格式千位以上
		if (type == 1) {
			if (number > 9999) {
				number = (number / 10000).toFixed(1) + 'w'
			} else if (number > 999) {
				number = (number / 1000).toFixed(1) + 'k'
			}
		}
		//格式百位
		if (type == 2 && number > 99) {
			number = '99+';
		}
		return number;
	},


	/**
	 * 时间格式化
	 * @param String timestamp 时间戳
	 * @param String fmt 返回的时间格式
	 * yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
	 */
	timeFormat(timestamp = null, fmt = 'yyyy-mm-dd') {
		// 其他更多是格式化有如下:
		// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
		timestamp = parseInt(timestamp);
		// 如果为null,则格式化当前时间
		if (!timestamp) timestamp = Number(new Date());
		// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
		if (timestamp.toString().length == 10) timestamp *= 1000;
		let date = new Date(timestamp);
		let ret;
		let opt = {
			"y+": date.getFullYear().toString(), // 年
			"m+": (date.getMonth() + 1).toString(), // 月
			"d+": date.getDate().toString(), // 日
			"h+": date.getHours().toString(), // 时
			"M+": date.getMinutes().toString(), // 分
			"s+": date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		for (let k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
	},

	/**
	 * 社交时间友好
	 * @param String timestamp 时间戳
	 * @param String | Boolean format 如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
	 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
	 */
	timeToDate(timestamp = null, format = 'yyyy-mm-dd') {
		if (timestamp == null) timestamp = Number(new Date());
		timestamp = parseInt(timestamp);
		// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
		if (timestamp.toString().length == 10) timestamp *= 1000;
		var timer = (new Date()).getTime() - timestamp;
		timer = parseInt(timer / 1000);
		// 如果小于5分钟,则返回"刚刚",其他以此类推
		let tips = '';
		switch (true) {
			case timer < 300:
				tips = '刚刚';
				break;
			case timer >= 300 && timer < 3600:
				tips = parseInt(timer / 60) + '分钟前';
				break;
			case timer >= 3600 && timer < 86400:
				tips = parseInt(timer / 3600) + '小时前';
				break;
			case timer >= 86400 && timer < 2592000:
				tips = parseInt(timer / 86400) + '天前';
				break;
			default:
				// 如果format为false，则无论什么时间戳，都显示xx之前
				if (format === false) {
					if (timer >= 2592000 && timer < 365 * 86400) {
						tips = parseInt(timer / (86400 * 30)) + '个月前';
					} else {
						tips = parseInt(timer / (86400 * 365)) + '年前';
					}
				} else {
					tips = timeFormat(timestamp, format);
				}
		}
		return tips;
	},



	/**
	 * @param {Number} len uuid的长度
	 * @param {Boolean} firstU 将返回的首字母置为"u"
	 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
	 */
	guid(len = 32, firstU = true, radix = null) {
		let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
		let uuid = [];
		radix = radix || chars.length;

		if (len) {
			// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
			for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
		} else {
			let r;
			// rfc4122标准要求返回的uuid中,某些位为固定的字符
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
			uuid[14] = '4';

			for (let i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16;
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
				}
			}
		}
		// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
		if (firstU) {
			uuid.shift();
			return 'u' + uuid.join('');
		} else {
			return uuid.join('');
		}
	},
	/**
	 * 页面跳转
	 * @param {Object} url 需要跳转的应用内非 tabBar 的页面的路径
	 * @param {Object} animationType 窗口显示的动画效果
	 * @param {Object} animationDuration 窗口动画持续时间，单位为 ms
	 */
	to(url, animationType = 'pop-in', animationDuration = 300) {
		uni.navigateTo({
			url,
			animationType,
			animationDuration,
			success: function(res) {
				console.log(res);
			},
			fail: function(e) {
				console.log(e);
			}
		})
	},

	/**
	 * 页面返回
	 * @param {Object} num 返回页面数量
	 */
	back(num = 1) {
		uni.navigateBack({
			delta: num
		});
	},
	/**
	 * 打开任意链接
	 * @param {Object} url 页面地址
	 */
	on(url) {
		url = decodeURIComponent(url);

		// 关闭所有页面，跳转链接
		if (url) {
			uni.switchTab({
				url: url
			});
		} else {
			to(url);
		}
	},
	/**
	 * 拨打电话 
	 * @param {JSON} number 电话号码
	 */
	phone(number) {

		uni.makePhoneCall({
			phoneNumber: number //仅为示例
		});
	},
	/**
	 * 复制文本
	 * @param {JSON} copy 复制文本
	 */
	copy(copy) {
		uni.setClipboardData({
		    data: copy,
		    success: function () {
		        console.log('success');
		    }
		});
	},
	/**
	 * 格式化kb
	 * @param {JSON} limit kb
	 */
	conver(limit) {
		return (limit / (1024 * 1024)).toFixed(1) + "MB";
	},










	/**
	 * fn：检测图片协议，主要用于检测海报图片协议。
	 * param(imgPath): 图片地址。
	 */

	checkImgHttp(imgPath) {
		let newPath = "";
		let pathArr = imgPath.split("://");
		// #ifdef H5
		let ishttps = "https:" == window.location.protocol ? true : false;
		ishttps ? (pathArr[0] = "https") : (pathArr[0] = "http");
		// #endif
		// #ifdef MP-WEIXIN
		pathArr[0] = "https";
		// #endif
		newPath = pathArr.join("://");
		return newPath;
	},


	// 图片处理-选择图片
	chooseImage(count = 1) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: count, //默认9
				sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ["album"], //从相册选择
				success: (res) => {
					console.log('res', res)
					resolve(res.tempFilePaths);
				},
			});
		}).catch((e) => {
			reject(e);
		});
	},
	// 图片处理-上传图片
	uploadImage(api, url) {
		let config_url = API_URL;
		uni.showLoading({
			title: "上传中",
		});
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: config_url + api,
				filePath: url,
				name: "file",
				success: (res) => {
					res = JSON.parse(res.data);
					if (res.code === 1) {
						uni.hideLoading();
						uni.showToast({
							title: "上传成功",
							icon: "none",
						});
						resolve(res.data);
					} else {
						uni.hideLoading();
						uni.showModal({
							title: "上传失败",
							content: res.msg,
						});
					}
				},
			});
		}).catch((e) => {
			reject(e);
		});
	},
	// 图片处理-预览图片
	previewImage(urls = [], current = 0) {
		uni.previewImage({
			urls: urls,
			current: current,
			indicator: "default",
			loop: true,
			fail(err) {
				console.log("previewImage出错", urls, err);
			},
		});
	},
	// 图片处理-获取图片信息
	getImageInfo(src = "") {
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: src,
				success: (image) => {
					resolve(image);
				},
				fail(err) {
					console.log("getImageInfo出错", src, err);
				},
			});
		}).catch((e) => {
			reject(e);
		});
	},








	/**提示框
	 *title(标题)
	 *icon(图标):  success，loading，none
	 *duration(延时): 0为不关闭, 毫秒数
	 *options(其它参数)
	 */
	// msg(title, direction, Num = 1) {
	// 	switch (Num) {
	// 		case 1:
	// 			direction.$refs.uToast.show({
	// 				title: title,
	// 				type: 'success'
	// 			});
	// 			break;
	// 		case 0:
	// 			direction.$refs.uToast.show({
	// 				title: title,
	// 				type: 'error'
	// 			});
	// 			break;
	// 	}
	// },

	msg(title, icon = 'none', options) {
		wx.showToast({
			title: title || '',
			icon: icon,
			duration: (options && options.duration) || 1500,
			image: (options && options.image) || '',
			mask: (options && options.mask) || true,
		});
	},


	/**提示框
	 *direction(this指向)
	 */

	load(direction, Num = 1) {
		switch (Num) {
			case 1:
				direction.$refs.loading.open();
				break;
			case 0:
				direction.$refs.loading.close();
				break;
		}
	},

	/**
	 *@alias 节流
	 *@param {function} fn 节流被执行函数
	 *@param {Number}  delay 时间单位内
	 */
	throttle(fn, delay) {
		let flag = true,
			timer = null;
		return function(...args) {
			let context = this;
			if (!flag) return;
			flag = false;
			clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(context, args);
				flag = true;
			}, delay);
		};
	},

	/**
	 *@alias 防抖
	 *@param {function} fn 防抖被执行函数
	 *@param {Number}  delay 时间单位内
	 */
	debounce(fn, delay) {
		let timer = null;
		return function(...args) {
			let context = this;
			if (timer) clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			}, delay);
		};
	},
	/**
	 * 将阿拉伯数字翻译成中文的大写数字
	 *  四仟五百六十二
	 */

	numberToChinese(num) {
		var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
		var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
		var a = ("" + num).replace(/(^0*)/g, "").split("."),
			k = 0,
			re = "";
		for (var i = a[0].length - 1; i >= 0; i--) {
			switch (k) {
				case 0:
					re = BB[7] + re;
					break;
				case 4:
					if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
						.test(a[0]))
						re = BB[4] + re;
					break;
				case 8:
					re = BB[5] + re;
					BB[7] = BB[5];
					k = 0;
					break;
			}
			if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
				re = AA[0] + re;
			if (a[0].charAt(i) != 0)
				re = AA[a[0].charAt(i)] + BB[k % 4] + re;
			k++;
		}

		if (a.length > 1) // 加上小数部分(如果有小数部分)
		{
			re += BB[6];
			for (var i = 0; i < a[1].length; i++)
				re += AA[a[1].charAt(i)];
		}
		if (re == '一十')
			re = "十";
		if (re.match(/^一/) && re.length == 3)
			re = re.replace("一", "");
		return re;
	},
	// 检测密码强度 等级1-5
	checkPwd(str) {
		var Lv = 1;
		if (str.length < 6) {
			return Lv
		}
		if (/[0-9]/.test(str)) {
			Lv++
		}
		if (/[a-z]/.test(str)) {
			Lv++
		}
		if (/[A-Z]/.test(str)) {
			Lv++
		}
		if (/[\.|-|_]/.test(str)) {
			Lv++
		}
		return Lv;
	},
	// 将数字转换为大写金额   肆仟伍佰陆拾贰元整
	changeToChinese(Num) {
		//判断如果传递进来的不是字符的话转换为字符
		if (typeof Num == "number") {
			Num = new String(Num);
		};
		Num = Num.replace(/,/g, "") //替换tomoney()中的“,”
		Num = Num.replace(/ /g, "") //替换tomoney()中的空格
		Num = Num.replace(/￥/g, "") //替换掉可能出现的￥字符
		if (isNaN(Num)) { //验证输入的字符是否为数字
			//alert("请检查小写金额是否正确");
			return "";
		};
		//字符处理完毕后开始转换，采用前后两部分分别转换
		var part = String(Num).split(".");
		var newchar = "";
		//小数点前进行转化
		for (var i = part[0].length - 1; i >= 0; i--) {
			if (part[0].length > 10) {
				return "";
				//若数量超过拾亿单位，提示
			}
			var tmpnewchar = ""
			var perchar = part[0].charAt(i);
			switch (perchar) {
				case "0":
					tmpnewchar = "零" + tmpnewchar;
					break;
				case "1":
					tmpnewchar = "壹" + tmpnewchar;
					break;
				case "2":
					tmpnewchar = "贰" + tmpnewchar;
					break;
				case "3":
					tmpnewchar = "叁" + tmpnewchar;
					break;
				case "4":
					tmpnewchar = "肆" + tmpnewchar;
					break;
				case "5":
					tmpnewchar = "伍" + tmpnewchar;
					break;
				case "6":
					tmpnewchar = "陆" + tmpnewchar;
					break;
				case "7":
					tmpnewchar = "柒" + tmpnewchar;
					break;
				case "8":
					tmpnewchar = "捌" + tmpnewchar;
					break;
				case "9":
					tmpnewchar = "玖" + tmpnewchar;
					break;
			}
			switch (part[0].length - i - 1) {
				case 0:
					tmpnewchar = tmpnewchar + "元";
					break;
				case 1:
					if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
					break;
				case 2:
					if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
					break;
				case 3:
					if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
					break;
				case 4:
					tmpnewchar = tmpnewchar + "万";
					break;
				case 5:
					if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
					break;
				case 6:
					if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
					break;
				case 7:
					if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
					break;
				case 8:
					tmpnewchar = tmpnewchar + "亿";
					break;
				case 9:
					tmpnewchar = tmpnewchar + "拾";
					break;
			}
			var newchar = tmpnewchar + newchar;
		}
		//小数点之后进行转化
		if (Num.indexOf(".") != -1) {
			if (part[1].length > 2) {
				// alert("小数点之后只能保留两位,系统将自动截断");
				part[1] = part[1].substr(0, 2)
			}
			for (i = 0; i < part[1].length; i++) {
				tmpnewchar = ""
				perchar = part[1].charAt(i)
				switch (perchar) {
					case "0":
						tmpnewchar = "零" + tmpnewchar;
						break;
					case "1":
						tmpnewchar = "壹" + tmpnewchar;
						break;
					case "2":
						tmpnewchar = "贰" + tmpnewchar;
						break;
					case "3":
						tmpnewchar = "叁" + tmpnewchar;
						break;
					case "4":
						tmpnewchar = "肆" + tmpnewchar;
						break;
					case "5":
						tmpnewchar = "伍" + tmpnewchar;
						break;
					case "6":
						tmpnewchar = "陆" + tmpnewchar;
						break;
					case "7":
						tmpnewchar = "柒" + tmpnewchar;
						break;
					case "8":
						tmpnewchar = "捌" + tmpnewchar;
						break;
					case "9":
						tmpnewchar = "玖" + tmpnewchar;
						break;
				}
				if (i == 0) tmpnewchar = tmpnewchar + "角";
				if (i == 1) tmpnewchar = tmpnewchar + "分";
				newchar = newchar + tmpnewchar;
			}
		}
		//替换所有无用汉字
		while (newchar.search("零零") != -1)
			newchar = newchar.replace("零零", "零");
		newchar = newchar.replace("零亿", "亿");
		newchar = newchar.replace("亿万", "亿");
		newchar = newchar.replace("零万", "万");
		newchar = newchar.replace("零元", "元");
		newchar = newchar.replace("零角", "");
		newchar = newchar.replace("零分", "");
		if (newchar.charAt(newchar.length - 1) == "元") {
			newchar = newchar + "整"
		}
		return newchar;
	},
	checkStr(str, type) {
		switch (type) {
			case 'phone': //手机号码
				return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
			case 'tel': //座机
				return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
			case 'card': //身份证
				return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
			case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
				return /^[a-zA-Z]\w{5,17}$/.test(str)
			case 'postal': //邮政编码
				return /[1-9]\d{5}(?!\d)/.test(str);
			case 'QQ': //QQ号
				return /^[1-9][0-9]{4,9}$/.test(str);
			case 'email': //邮箱
				return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
			case 'money': //金额(小数点2位)
				return /^\d*(?:\.\d{0,2})?$/.test(str);
			case 'URL': //网址
				return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
			case 'IP': //IP
				return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
			case 'date': //日期时间
				return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
					/^(\d{4})\-(\d{2})\-(\d{2})$/
					.test(str)
			case 'number': //数字
				return /^[0-9]$/.test(str);
			case 'english': //英文
				return /^[a-zA-Z]+$/.test(str);
			case 'chinese': //中文
				return /^[\\u4E00-\\u9FA5]+$/.test(str);
			case 'lower': //小写
				return /^[a-z]+$/.test(str);
			case 'upper': //大写
				return /^[A-Z]+$/.test(str);
			case 'HTML': //HTML标记
				return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
			default:
				return true;
		}
	}




};
